#include "CardBussiness.h"
#include <Windows.h>
#include "DatabaseAccess.h"
#include "common.h"

CCardBussiness::CCardBussiness(void)
{
}

CCardBussiness::~CCardBussiness(void)
{
}

//Ham check validate cua card
bool CCardBussiness::CheckValidateCard(char* g_sCardIDInput, HWND hWnd)
{
    if (g_sCardIDInput[0] == 0)
    {
        MessageBox(hWnd, CARD_INVALID, CARD_ERROR_CAPTION, MB_ICONERROR);
        return false;
    }
    if (strlen(g_sCardIDInput) != LENGTH_CARDID)
    {
        MessageBox(hWnd, LENGTH_CARD_INVALID, CARD_ERROR_CAPTION, MB_ICONERROR);
        return false;
    }
	g_Card.SetCardID(g_sCardIDInput);
	CDatabaseAccess objDAO;
	bool bCheckExistCard = objDAO.ReadFileCard(g_Card, FILE_CARD);
    if (!bCheckExistCard)
    {
        MessageBox(hWnd, CARD_INVALID, CARD_ERROR_CAPTION, MB_ICONERROR);
        return false;
    }
	if (g_Card.GetCardStatus() == CS_LOCK)
	{
		MessageBox(hWnd, CARD_LOCKED, CARD_LOCKED_CAPTION, MB_ICONERROR);
		return false;
	}
	if (g_Card.GetCardStatus() == CS_LOCK_TMP)
	{
		MessageBox(hWnd, CARD_LOCKED_TMP, CARD_LOCKED_CAPTION, MB_ICONERROR);
		return false;
	}
	return true;
}

//Ham check xem ma PIN co dung khong
bool CCardBussiness::CheckValidPIN(const char* sPINInput, const char* sPINCard)
{
    if (strlen(sPINInput) != LENGTH_PIN)
        return false;
    return (strcmp(sPINInput, sPINCard) == 0);
}

//Ham check authenticate user
int CCardBussiness::CheckUserAuth(const char* sPINInput, const char* sPINCard)
{
    CDatabaseAccess objDAO;
    if (!CheckValidPIN(sPINInput, sPINCard))
    {
        g_nCount--;
        if (g_nCount == 0)
        {           
            g_Card.SetCardStatus(CS_LOCK_TMP);
            objDAO.WriteFileCard(g_Card, FILE_CARD);
            g_nCount = MAX_INVALID;
            return INVALID_PIN_LOCK;
        }
        return INVALID_PIN; 
    }  
    g_Account.SetAccountID(g_Card.GetAccountID());
    objDAO.ReadFileAccount(g_Account, FILE_ACCOUNT);
    return VALID_PIN;
}

bool CCardBussiness::CheckNewPIN(char* sNewPIN, const char* sNewPINRepeat)
{
    if (strcmp(sNewPIN, sNewPINRepeat) == 0)
    {
        CDatabaseAccess objDAO;
        g_Card.SetPin(sNewPIN);
        objDAO.WriteFileCard(g_Card, FILE_CARD);
        return true;
    }
    return false;
}